<template>
  <div class="tpl-container">
    <div class="mb20 condition-container">
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('物料描述') }}：</span>
        <ElInput
          v-model="itemname"
          class="w192 mr14"
          :placeholder="translate('请输入物料描述')"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('物料编码') }}：</span>
        <ElInput
          v-model="itemcode"
          class="w192"
          :placeholder="translate('请输入物料编码')"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('单位') }}：</span>
        <el-autocomplete
          v-model="whUnit"
          class="inline-input"
          :fetch-suggestions="querySearch"
          placeholder="选择单位"
          @select="handleSelect"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('存放地点') }}：</span>
        <ElInput
          v-model="storageLocation"
          class="w192"
          :placeholder="translate('请输入存放地点')"
        />
      </div>
      <div class="condition">
        <el-select
          v-model="stockType"
          class="w120"
          :placeholder="translate('全部数量')"
        >
          <el-option
            v-for="item in numberType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <ElInput
          v-model="stockQty"
          class="w192 mr14"
          :placeholder="translate('请输入数量')"
          type="number"
        />
      </div>
        <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('库架层位') }}：</span>
        <ElInput
          v-model="wsCode"
          class="w192 mr14"
          :placeholder="translate('请输入库架层位')"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('批次号') }}：</span>
        <ElInput
          v-model="batchNo"
          class="w192"
          :placeholder="translate('请输入批次号')"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('仓储管理员') }}：</span>
        <ElInput
          v-model="whManage"
          class="w192"
          :placeholder="translate('请输入仓储管理员')"
        />
      </div>
      <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('是否能用') }}：</span>
        <el-select
            v-model="stockStatus"
            class="w192"
            :placeholder="translate('请选择')"
              >
              <el-option
                v-for="item in stockStatusArry"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
              </el-select>
        <ElButton class="settingBtn ml10" type="primary" @click="search">
          {{ translate('查询') }}
        </ElButton>
      </div>
      <!-- <div class="condition">
        <span class="color_494949 ft12 pr5">{{ translate('到货时间') }}：</span>
        <el-date-picker
            class="mr14"
            v-model="dateTime"
            end-placeholder="结束日期"
            range-separator="至"
            start-placeholder="开始日期"
            type="daterange"
            value-format="YYYY-MM-DD"
          />
        <ElButton class="settingBtn ml10" type="primary" @click="search">
          {{ translate('查询') }}
        </ElButton>
      </div> -->
    </div>
    <div class="add">
        <ElButton type="primary" @click="download()" plain>
          {{ translate('模板') }}
        </ElButton>
        <!-- <el-upload
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :action="action"
          :before-upload="beforeUpload"
          class="ml-upload"
          :headers="headers"
          name="fileInput"
          :on-error="handleError"
          :on-success="handleSuccess"
          :show-file-list="false"
        >
          <ElButton type="primary" @click="uploadFn()" plain>
            {{ translate('导入') }}
          </ElButton>
        </el-upload> -->
        <ElButton type="primary" @click="exportFn()" plain>
          {{ translate('导出') }}
        </ElButton>
        <ElButton type="primary" @click="batchFn()" plain>
          {{ translate('批量修改名称') }}
        </ElButton>
        <ElButton type="primary" @click="batchDPFn()" plain>
          {{ translate('批量修改部门') }}
        </ElButton>
        <ElButton type="primary" @click="batchDPFn2()" plain>
          {{ translate('批量修改单位') }}
        </ElButton>
        <ElButton type="primary" @click="deletedBatchFn()" plain>
          {{ translate('批量删除') }}
        </ElButton>
        <ElButton type="primary" @click="dateBatchFn()" plain>
          {{ translate('修改到货时间') }}
        </ElButton>
      </div>
    <div class="table">
      <ElTable
        ref="multipleTableRef"
        v-loading="loading"
        :border="true"
        :data="tableData"
        :row-class-name="tableRowClassName"
        :row-key="getRowKey"
        @selection-change="handleSelectionChange"
        show-summary
        :summary-method="totalOutYear"
      >
       <ElTableColumn
          prop="value"
          type="selection"
          width="auto"
        />
        <!-- <ElTableColumn :label="translate('部门名称')">
          <template #default="{ row }">
            <div>
              <span :class="row.WHUnit != row.DeptName?'color_red':''">{{ row.DeptName }}</span>
            </div>
          </template>
        </ElTableColumn> -->
        <ElTableColumn
          :label="translate('仓库单位')"
          prop="WHUnit"
          width="auto"
        />
        <ElTableColumn
          :label="translate('存放地点')"
          prop="StorageLocation"
          width="auto"
        />
        <ElTableColumn
          :label="translate('库架层位')"
          prop="WSCode"
          width="auto"
        />
        <ElTableColumn :label="translate('类别')" width="60">
          <template #default="{ row }">
            <div>
              <span>{{ row.ItemCate }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('批次号')">
          <template #default="{ row }">
            <div>
              <span>{{ row.BatchNo }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('物料编码')">
          <template #default="{ row }">
            <div @dblclick="dblclicks(row)">
              <span>{{ row.ItemCode }}</span>
            </div>
          </template>
        </ElTableColumn>
        <!-- <ElTableColumn :label="translate('物资类型')">
          <template #default="{ row }">
            <div>
              <span>{{ row.Owner }}</span>
            </div>
          </template>
        </ElTableColumn> -->
        <!-- <ElTableColumn
          :label="translate('物料名称')"
          prop="ItemName"
          width="auto"
        />
        <ElTableColumn
          :label="translate('物料规格')"
          prop="ItemSpec"
          width="auto"
        /> -->
         <ElTableColumn :label="translate('物料描述')">
          <template #default="{ row }">
            <div>
              <span>{{ row.ItemName +'/'+ row.ItemSpec}}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          :label="translate('计量单位')"
          prop="ItemUnit"
          width="55"
        />
        <ElTableColumn :label="translate('数量')" prop="StockQty" sortable>
          <template #default="{ row }">
            <div>
              <span class="color_red">{{ row.StockQty }}</span>
              <vab-icon v-if="realname.indexOf('张杨') !== -1"  icon="edit-line" @click="exitStockQty(row)" />
            </div>
          </template>
        </ElTableColumn>
        <!-- <ElTableColumn
          :label="translate('出库数量')"
          prop="OQty"
          width="auto"
        />
        <ElTableColumn
          :label="translate('入库数量')"
          prop="IQty"
          width="auto"
        /> -->
        <ElTableColumn :label="translate('单价')">
          <template #default="{ row }">
            <div>
              <span>{{ row.Price }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('金额')" prop="Amt" width="auto" sortable />
        <ElTableColumn :label="translate('仓储管理员')">
          <template #default="{ row }">
            <div>
              <span>{{ row.WHManage }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('预警天数')">
          <template #default="{ row }">
            <div>
              <span :class="row.SortCode > 60?'color_red':''">{{ row.SortCode }}</span>
            </div>
          </template>
        </ElTableColumn>
        <!-- <ElTableColumn :label="translate('电话')">
          <template #default="{ row }">
            <div>
              <span>{{ row.WHManageTel }}</span>
            </div>
          </template>
        </ElTableColumn> -->
        <ElTableColumn :label="translate('供应厂家')">
          <template #default="{ row }">
            <div>
              <span>{{ row.SupName }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('到货时间')">
          <template #default="{ row }">
            <div @dblclick="dateEtitFn(row)">
              <span>{{ row.ArrivalTime }}</span>
            </div>
          </template>
        </ElTableColumn>
        <!-- <ElTableColumn
          :label="translate('到货时间')"
          prop="ArrivalTime"
          width="auto"
        /> -->
        <ElTableColumn
          :label="translate('创建人')"
          prop="CreateUserName"
          width="auto"
        />
        <ElTableColumn
          align="center"
          :label="translate('是否能用')"
          width="55"
        >
          <template #default="{ row }">
            <div>
              {{ row.StockStatus }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn align="center" :label="translate('图片')">
          <template #default="{ row }">
            <div v-if="row.ModifyUserName">
              <div :key="index">
                <el-image
                  v-if="row.imglist[0]"
                  fit="contain"
                  :initial-index="9"
                  :preview-src-list="row.imglist"
                  :preview-teleported="true"
                  :src="row.imglist[0]"
                  style="width: 60px; height: 60px"
                  :z-index="99999"
                  :zoom-rate="1.2"
                />
              </div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn align="center" :label="translate('图片1')" width="150">
          <template #default="{ row }">
            <div v-if="row.Field1">
              <div :key="index">
                <el-image
                  v-if="row.imglist1[0]"
                  fit="contain"
                  :initial-index="0"
                  :preview-src-list="row.imglist1"
                  :preview-teleported="true"
                  :src="row.imglist1[0]"
                  style="width: 60px; height: 60px"
                  :z-index="99999"
                  :zoom-rate="1.2"
                />
                <el-image
                  v-if="row.imglist1[1]"
                  fit="contain"
                  :initial-index="1"
                  :preview-src-list="row.imglist1"
                  :preview-teleported="true"
                  :src="row.imglist1[1]"
                  style="width: 60px; height: 60px"
                  :z-index="99999"
                  :zoom-rate="1.2"
                />
              </div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('备注')">
          <template #default="{ row }">
            <div>
              <span>{{ row.Remark }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn align="center" :label="translate('操作')" width="320">
          <template #default="{ row }">
            <div>
              <!-- <ElButton v-if="MenuAuth('edit')" size="small" plain type="primary" @click="dateEtitFn(row)">
                {{ translate('到货时间') }}
              </ElButton> -->
              <ElButton v-if="MenuAuth('edit')" size="small" plain type="primary" @click="eitFn(row)">
                {{ translate('修改库位') }}
              </ElButton>
              <ElButton v-if="MenuAuth('edit')" size="small" plain type="primary" @click="showDialog(row)">
                {{ translate('编辑') }}
              </ElButton>
              <ElButton v-if="MenuAuth('delete')" size="small" plain type="danger" @click="deleteFn(row)">
                {{ translate('删除') }}
              </ElButton>
            </div>
          </template>
        </ElTableColumn>
      </ElTable>
      <div v-if="total > 0" class="pagination">
        <ElPagination
          background
          :current-page="searchInfo.pageNo"
          :layout="layout"
          :page-size="searchInfo.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <Dialog
      :info="detail"
      :visible="dialogVisible"
      @close="handleClose"
      @confirm="handleConfirm"
    />
    <el-dialog
      v-model="dialogVisible1"
      :before-close="handleClose1"
      :title="translate('详情')"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="flex_align">
        <div class="mr20">
          <span class="w90 color_494949 ft12 pr5">
            {{ translate('新物资名称') }}：
          </span>
          <el-input v-model="newFullName" class="w192" />
        </div>
        <div class="mr20">
          <ElButton class="settingBtn" type="primary" @click="addWmsList">
            {{ translate('添加物资') }}
          </ElButton>
        </div>
      </div>
      <div>
        <div class="mr20 mt10">
          <span class="w90 color_494949 ft12 pr5">
            {{ translate('新价格') }}：
          </span>
          <el-input v-model="newprice" class="w192" />
        </div>
        <div class="mr20 mt10">
          <span class="w90 color_494949 ft12 pr5">
            {{ translate('新单位') }}：
          </span>
          <el-input v-model="newitemUnit" class="w192" />
        </div>
      </div>
      <div class="flex_align mt20">
        <div class="mr20">
          <!-- <span class="color_494949 ft12 pr5">{{ translate('修改的物资') }}：</span> -->
          <div class="w400 inline-block">
            <el-tag
              v-for="tag in selectArr"
              :key="tag.ItemCode"
              class="mx-1"
              closable
              @close="closeFn(tag)"
            >
              {{ tag.ItemName }}
            </el-tag>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="handleClose1">{{ translate('取消') }}</el-button>
        <el-button type="primary" @click="confirm1">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisible2"
      :before-close="handleClose2"
      :title="translate('批量修改部门')"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="flex_align">
        <el-select
          v-model="DepartmentId"
          class="w200"
          :placeholder="translate('请选择部门')"
        >
          <el-option
            v-for="item in WHdata"
            :key="item.DepartmentId"
            :label="item.FullName"
            :value="item.DepartmentId"
          />
        </el-select>
      </div>
      <template #footer>
        <el-button @click="handleClose2">{{ translate('取消') }}</el-button>
        <el-button type="primary" @click="confirm2">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisible3"
      :before-close="handleClose3"
      :title="translate('批量修改库位')"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="flex_align">
        <span>原库位：</span>
        <el-tag>{{ wmscodename }}</el-tag>
      </div>
      <div class="flex_align mt10">
        <span>新库位：</span>
        <ElInput
          v-model="WHdataId"
          class="w192 mr14"
          :placeholder="translate('请输入库位名称')"
        />
        <!-- <el-select
          v-model="WHdataId"
          class="w200"
          :placeholder="translate('请选择库位')"
        >
          <el-option
            v-for="item in WHdata1"
            :key="item.WHAID"
            :label="item.FullName"
            :value="item.WHAID"
          />
        </el-select> -->
      </div>
      <template #footer>
        <el-button @click="handleClose3">{{ translate('取消') }}</el-button>
        <el-button type="primary" @click="confirm3">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogChiled"
      :title="translate('选择物资')"
      width="800px"
    >
      <div style="padding-bottom: 20px">
        <span class="color_494949 ft12 pr5">{{ translate('关键字') }}：</span>
        <el-input
          v-model="searchChild"
          class="w192 mr10"
          :placeholder="translate('请输入关键字')"
        />
        <el-button
          class="settingBtn mr10"
          type="primary"
          @click="search1('seach')"
        >
          {{ translate('查询') }}
        </el-button>
        <!-- <span class="color_494949 ft12 pr5">{{ translate('单位') }}：</span>
        <el-input
          v-model="searchWHUnit"
          class="w192 mr10"
          :placeholder="translate('请输入单位')"
        /> -->
        <!-- <div class="mt10">
          <span class="color_494949 ft12 pr5">
            {{ translate('存放地点') }}：
          </span>
          <el-input
            v-model="searchStorageLocation"
            class="w192 mr10"
            :placeholder="translate('请输入存放地点')"
          />
          <el-button
            class="settingBtn mr10"
            type="primary"
            @click="WmsGetPageData02('seach')"
          >
            {{ translate('查询') }}
          </el-button>
        </div> -->
      </div>
      <div>
        <el-table
          ref="multipleTable"
          border
          :data="tableData1"
          height="400"
          style="width: 800px"
          @row-click="clickrow"
          @selection-change="handleSelectionChangechiled"
        >
          <el-table-column prop="value" type="selection" width="55" />
          <el-table-column :label="translate('仓库单位')" prop="WHUnit" />
          <el-table-column :label="translate('物资编码')" prop="ItemCode" />
          <el-table-column :label="translate('物资名称')" prop="ItemName" />
          <el-table-column :label="translate('单位')" prop="ItemUnit" />
          <el-table-column :label="translate('规格')" prop="ItemSpec" />
          <el-table-column :label="translate('库存')" prop="StockQty" />
          <el-table-column
            :label="translate('存放地点')"
            prop="StorageLocation"
          />
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            :current-page="searchInfo1.pageNo"
            :layout="layout"
            :page-size="searchInfo1.pageSize"
            :total="total1"
            @current-change="handleCurrentchiled"
            @size-change="handleSizechiled"
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="dialogChiled = false">
          {{ translate('取消') }}
        </el-button>
        <el-button type="primary" @click="submitChiled()">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisible4"
      :before-close="handleClose4"
      :title="translate('修改到货时间')"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="flex_align">
        <span class="color_494949 ft12 pr5">{{ translate('到货时间：') }}：</span>
        <el-date-picker
          v-model="datetime"
          style="width: 164px"
          type="date"
          value-format="YYYY-MM-DD"
        />
      </div>
      <template #footer>
        <el-button @click="handleClose4">{{ translate('取消') }}</el-button>
        <el-button type="primary" @click="confirm4">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisible5"
      :title="translate('修改库存数量')"
      width="400px"
      @close="closeFn5"
    >
      <div>
        <span class="w120 color_494949 ft12 pr5">{{ translate('库存数量') }}：</span>
        <ElInput
          type="number"
          v-model="sotckQty"
          class="w164 mr14"
          :placeholder="translate('请输入库存数量')"
        />
      </div>
      <template #footer>
        <el-button @click="dialogVisible5 = false">
          {{ translate('取消') }}
        </el-button>
        <el-button type="primary" @click="submit">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisible6"
      :before-close="handleClose6"
      :title="translate('批量修改单位')"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="flex_align">
        <el-select
          v-model="DepartmentId"
          class="w200"
          :placeholder="translate('请选择单位')"
        >
          <el-option
            v-for="item in DWdata"
            :key="item.FullName"
            :label="item.FullName"
            :value="item.FullName"
          />
        </el-select>
      </div>
      <template #footer>
        <el-button @click="handleClose6">{{ translate('取消') }}</el-button>
        <el-button type="primary" @click="confirm6">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisible7"
      :title="translate('修改物料编码')"
      width="400px"
      @close="closeFn7"
    >
      <div>
        <span class="w120 color_494949 ft12 pr5">{{ translate('物料编码') }}：</span>
        <span>{{itemcodeEDIT}}</span>
      </div>
      <div class="mt20">
        <span class="w120 color_494949 ft12 pr5">{{ translate('新物料编码') }}：</span>
        <ElInput
          type="text"
          v-model="itemcodeEDITNew"
          class="w164 mr14"
          :placeholder="translate('请输入新的物料编码')"
        />
      </div>
      <template #footer>
        <el-button @click="dialogVisible7 = false">
          {{ translate('取消') }}
        </el-button>
        <el-button type="primary" @click="submit7">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import {
    WmsGetPageData,
    Wms_ItemStockDown,
    Wms_ItemStockExport,
    delstock,
    batchitemname,
    batchdelstock,
    batchdeptid,
    batcharrivaltime,
    correctstock,
    batchwhunit,
    edititemcode,
  } from '@/api/mupro'
  import router from '@/router'
  import { GetPageDataVisit, BaseGetPageData } from '@/api/item'
  import { WHGetPageData, tranwscode } from '@/api/form'
  import Dialog from './components/dialog.vue'
  import { useUserStore } from '@/store/modules/user'
  import { translate } from '@/i18n'
  import { baseURL } from '@/config'
  import { parseTime } from '@/utils'
  import { MenuAuth } from '~/src/utils/permission'
  const userStore = useUserStore()
  const { realname } = storeToRefs(userStore)
  const { token } = useUserStore()
  const itemname = ref('')
  const itemcode = ref('')
  const whUnit = ref('')
  const storageLocation = ref('')
  const PayLoadTopic = ref('')
  const date = ref('')
  const datetime = ref()
  const wsCode = ref('')
  const stockStatusArry = ref([
  {
      label: '全部',
      value: '',
    },
    {
      label: '是',
      value: '是',
    },
    {
      label: '否',
      value: '否',
    },
    {
      label: '联',
      value: '联',
    },
  ])
  const stockStatus = ref('')
  const  route  = useRoute()
  const batchNo = ref('')
  const whManage = ref('')
  const searchInfo1 = reactive({
    pageNo: 1,
    pageSize: 10,
    tableName: '',
    sort: '',
    order: '',
    wheres: `[{"name":"ItemCode","value":${itemcode.value},"displayType":"like"},
              {"name":"ItemCode","value":${storageLocation.value},"displayType":"like"},
              {"name":"WHUnit","value":${whUnit.value},"displayType":"like"}]`,
    export: false,
    value: '',
  })
  const searchInfo = reactive({
    pageNo: 1,
    pageSize: 10,
    tableName: '',
    sort: '',
    order: '',
    wheres: `[{"name":"ItemName","value":${itemname.value},"displayType":"like"},
              {"name":"ItemCode","value":${itemcode.value},"displayType":"like"},
              {"name":"ItemCode","value":${storageLocation.value},"displayType":"like"},
              {"name":"WSCode","value":${wsCode.value},"displayType":"like"},
              {"name":"StockStatus","value":${stockStatus.value},"displayType":"like"},
              {"name":"BatchNo","value":${batchNo.value},"displayType":"like"},
              {"name":"WHManage","value":${whManage.value},"displayType":"like"},
              {"name":"WHUnit","value":${whUnit.value},"displayType":"like"}]`,
    export: false,
    value: '',
  })
  const loading = ref(false)
  const action = ref('')
  const layout = ref('total, sizes, prev, pager, next, jumper')
  const tableData = ref([])
  const tableData1 = ref([])
  const total = ref(0)
  const total1 = ref(0)
  const listLoading = ref(false)
  const headers = ref('')
  const WHdata = ref([])
  const WHdata1 = ref([])
  const DWdata = ref([])
  const newFullName = ref('')
  const newitemUnit = ref('')
  const newprice = ref('')
  const dialogChiled = ref(false)
  const seletcdArr = ref([])
  const multipleTable = ref(null)
  const selectArr = ref([])
  const seletceInfo = ref('')
  const searchChild = ref('')
  const searchChild1 = ref('')
  const selectArrList = ref([])
  const dialogVisible2 = ref(false)
  const dialogVisible3 = ref(false)
  const dialogVisible4 = ref(false)
  const dialogVisible6 = ref(false)
  const dialogVisible7 = ref(false)
  const DepartmentId = ref('')
  const WHdataId = ref('')
  const wmscodename = ref('')
  const itemcodeEDIT = ref('')
  const itemcodeEDITNew = ref('')
  const ISIDNo = ref('')
  // const dateTime = ref([])
  // console.log(dateTime.value)
  const dialogVisible5 = ref(false)
  const selectInfo = ref('')
  const sotckQty = ref('')
  const numberType = ref([
    {
      label: '全部',
      value: '',
    },
    {
      label: '数量大于',
      value: 'GT',
    },
    {
      label: '数量小于',
      value: 'LT',
    },
    {
      label: '数量等于',
      value: 'Equal',
    },
  ])

  const stockType = ref('')
  const stockQty = ref('')
  // 获取表格数据
  const gettableData = async (val: any) => {
    const params = searchInfo
    console.log(route.path)
    params.openid = route.path === '/ItemStocks/wmsitemstock1' ? '技术中心': (route.path === '/ItemStocks/wmsitemstock2' ? '基建项目' : route.path === '/ItemStocks/wmsitemstock3'?'应急物资':'')
    loading.value = true
    const { data } = await WmsGetPageData(params)
    loading.value = false
    // console.log(data)
    if (data.rows) {
      data.rows.map((item) => {
        if (
          item.ModifyUserName &&
          item.ModifyUserName != null &&
          item.ModifyUserName != 'null'
        ) {
          item.imglist = []
          item.ModifyUserName = JSON.parse(item.ModifyUserName)
          item.ModifyUserName.map((item1) => {
            item.imglist.push(item1.FilePath)
          })
        }
        if (item.Field1&&item.Field1!=null&&item.Field1!='null') {
          item.imglist1 = []
          item.Field1 = JSON.parse(item.Field1)
          item.Field1.map((item1) => {
            item.imglist1.push(item1.FilePath)
          })
        }
      })
    }

    tableData.value = data?.rows || []
    total.value = data?.total || 0
  }
  const totalOutYear = (param) => {
      const { columns, data } = param

      const sums = []

      columns.forEach((column, index) => {

        if (index === 0) {

          sums[index] = "合计"

          return

        }
        if (index === 1 || index === 2 || index === 3 || index === 4 || index === 5 || index === 6 || index === 7 ||
            index === 8 || index === 9 || index === 10 || index === 11 || index === 13 ||index === 15||index === 16 ||
            index === 17||index === 18||index === 19||index === 20||index === 21||index === 22||index === 23) {

          sums[index] = " "

          return

          }

        const values = data.map(item => Number(item[column.property]))

        if (
          column.property != "BatchNo" && column.property != "WHUnit" &&
          column.property != "StorageLocation" && column.property != "WSCode" &&
          column.property != "ItemCate" && column.property != "ItemCode" &&
          column.property != "Owner" && column.property != "ItemSpec"
        ) {

          sums[index] = values.reduce((prev, curr) => {

            const value = Number(curr);
            if (!isNaN(value)) {
              const tt = prev*1 + curr*1
              if(Number.isInteger(tt)) {
                return tt.toString()
              }else {
                console.log(tt)
                return tt.toFixed(2)
              }


            } else {

              return prev

            }

          }, 0)

          sums[index]

        }

      })

      return sums

      }
  const WHGetPageData2 = async () => {
    const params = {
          pageNo: 1,
          pageSize: 100,
          wheres: `[{"name":"ModuleId","value":"","displayType":"equal"}]`,
          export: true,
          moduleType: 'ModuleId',
          sort: 'SortCode',
          order: 'ASC',
          search: '',
    }
    const { data } = await WHGetPageData(params)
       WHdata1.value = data.rows
  }
  const gettableData1 = async (val: any) => {
    // loading.value = true
    const { data } = await WmsGetPageData(searchInfo1)
    // loading.value = false
    // console.log(data)
    if (data.rows) {
      data.rows.map((item) => {
        if (
          item.ModifyUserName &&
          item.ModifyUserName != null &&
          item.ModifyUserName != 'null'
        ) {
          item.imglist = []
          item.ModifyUserName = JSON.parse(item.ModifyUserName)
          item.ModifyUserName.map((item1) => {
            item.imglist.push(item1.FilePath)
          })
        }
      })
    }
    tableData1.value = data?.rows || []
    total1.value = data?.total || 0
  }
  gettableData()
  // WHGetPageData2()
  const $baseConfirm = inject('$baseConfirm') as any
  const deleteFn = async (row: any) => {
    $baseConfirm(translate('你确定要删除当前项吗'), null, async () => {
      const data = await delstock({
        sid: row.ISID,
      })
      if (data.code === '200') {
        ElMessage({
          message: data.message,
          type: 'success',
        })
      }
      gettableData()
    })
  }
    //  修改库存数量
    const exitStockQty = (val: any) => {
        selectInfo.value = val.ISID
        dialogVisible5.value = true
  }
  const closeFn5 = () => {
    dialogVisible5.value = false
  }
  const submit7 = async () => {
    if(!itemcodeEDITNew.value) {
      ElMessage({
          message: '请填写新的物料编码',
          type: 'warning',
        })
        return
    }
    $baseConfirm(translate('你确定要修改物料编码？'), null, async () => {
      const data = await edititemcode({
        isid: ISIDNo.value,
        itemCode: itemcodeEDITNew.value
      })
      if (data.code === '200') {
        dialogVisible7.value = false
        ElMessage({
          message: data.message,
          type: 'success',
        })
      }
      gettableData()
    })

  }
  const submit = async () => {
      const params = {
         isid: selectInfo.value,
         stockQty: sotckQty.value
      }
      const data = await correctstock(params)
      if(data.code === '200') {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          dialogVisible5.value = false
          gettableData()
      }else {
        ElMessage({
          message: data.message,
          type: 'error',
        })
      }
  }
  const deletedBatchFn =async (row: any) => {
    const arrList = []
    if(selectArrList.value&&selectArrList.value.length>0) {
      selectArrList.value.map((item) =>{
        arrList.push({
          sid: item.ISID
        })
      })
    }else {
      ElMessage({
          message: '请选择至少一条要删除的数据',
          type: 'warning',
        })
      return
    }
    $baseConfirm(translate('你确定要删除吗'), null, async () => {
      const data = await batchdelstock(arrList)
      if (data.code === '200') {
        ElMessage({
          message: data.message,
          type: 'success',
        })
      }
      gettableData()
    })
  }
   const tableRowClassName = ({ row, rowIndex }) => {
        row.row_index = rowIndex
  }
  const getRowKey = (row) => {
        return row.ISID
  }
  const handleSelectionChange = (e) => {
       selectArrList.value = e
       console.log(selectArrList.value)
  }
  //分页条数切换
  const handleSizeChange = (val: any) => {
    searchInfo.pageSize = val
    gettableData()
  }
  //分页切换
  const handleCurrentChange = (val: any) => {
    searchInfo.pageNo = val
    gettableData()
  }
  //分页条数切换
  const handleSizechiled = (val: any) => {
    searchInfo1.pageSize = val
    gettableData('seach')
  }
  //分页切换
  const handleCurrentchiled = (val: any) => {
    searchInfo1.pageNo = val
    gettableData('seach')
  }
  const handleSelect = (item) => {
    console.log(item)
  }
  const addWmsList = () => {
    searchInfo1.pageSize = 20
    searchInfo1.pageNo = 1
    seletcdArr.value = []
    dialogChiled.value = true
    gettableData1()
  }
  const dblclicks = (val) =>{
    itemcodeEDIT.value = val.ItemCode
    ISIDNo.value = val.ISID
    itemcodeEDITNew.value = ''
    dialogVisible7.value = true
  }
  const clickrow = (row: any) => {
    const selected = seletcdArr.value.some((item) => item.ISID === row.ISID)
    if (!selected) {
      seletcdArr.value.push(row)
      multipleTable.value.toggleRowSelection(row, true)
    } else {
      const finaArr = seletcdArr.value.filter((item) => item.ISID !== row.ISID)
      seletcdArr.value = finaArr
      multipleTable.value.toggleRowSelection(row, false)
    }
    console.log(seletcdArr.value)
  }
  const submitChiled = () => {
    const arrChiled = selectArr.value
    seletcdArr.value.map((item) => {
      let istrue = false
      if (arrChiled.length > 0) {
        arrChiled.map((item2) => {
          if (item.ItemCode === item2.ItemCode) {
            istrue = true
          }
        })
      }
      if (!istrue) {
        arrChiled.push(item)
      }
    })
    nextTick(() => {
      selectArr.value = arrChiled
    })
    dialogChiled.value = false
    console.log(selectArr.value)
  }
  const confirm1 = async () => {
    seletceInfo.value = ''
    if (selectArr.value && selectArr.value.length > 0) {
      const arr = []
      selectArr.value.map((item) => {
        arr.push(item.ISID)
      })
      seletceInfo.value = arr.join(';')
    }
    const params = {
      listISID: seletceInfo.value,
      itemName: newFullName.value,
      itemUnit: newitemUnit.value,
      price: newprice.value*1,
    }
    const data = await batchitemname(params)
    if (data.code === '200') {
      ElMessage({
        message: data.message,
        type: 'success',
      })
      dialogVisible1.value = false
      gettableData()
    }
  }
  const confirm2 = async () => {
    seletceInfo.value = ''
    if (selectArrList.value && selectArrList.value.length > 0) {
      const arr = []
      selectArrList.value.map((item) => {
        arr.push(item.ISID)
      })
      seletceInfo.value = arr.join(';')
    }
    const params = {
      listISID: seletceInfo.value,
      deptID: DepartmentId.value,
    }
    const data = await batchdeptid(params)
    if (data.code === '200') {
      ElMessage({
        message: data.message,
        type: 'success',
      })
      dialogVisible2.value = false
      gettableData()
    }
  }
  const confirm6 = async () => {
    seletceInfo.value = ''
    if (selectArrList.value && selectArrList.value.length > 0) {
      const arr = []
      selectArrList.value.map((item) => {
        arr.push(item.ISID)
      })
      seletceInfo.value = arr.join(';')
    }
    const params = {
      listISID: seletceInfo.value,
      whUnit: DepartmentId.value,
    }
    const data = await batchwhunit(params)
    if (data.code === '200') {
      ElMessage({
        message: data.message,
        type: 'success',
      })
      dialogVisible6.value = false
      gettableData()
    }
  }
  const confirm4 = async () => {
    seletceInfo.value = ''
    console.log(selectArrList.value)
    if (selectArrList.value && selectArrList.value.length > 0) {
      const arr = []
      selectArrList.value.map((item) => {
        arr.push(item.ISID)
      })
      console.log(seletceInfo.value)
      seletceInfo.value = arr.join(',')
    }
    const params = {
      listISID: seletceInfo.value,
      arrivalTime: datetime.value,
    }
    const data = await batcharrivaltime(params)
    if (data.code === '200') {
      ElMessage({
        message: data.message,
        type: 'success',
      })
      dialogVisible4.value = false
      gettableData()
    }
  }
  const closeFn = (tag) => {
    selectArr.value.splice(selectArr.value.indexOf(tag), 1)
  }
  const querySearch = (queryString, cb) => {
    const restaurants = WHdata.value
    const results =
      queryString && queryString != 'null'
        ? restaurants.filter(createFilter(queryString))
        : restaurants
    console.log(results)
    // 调用 callback 返回建议列表的数据
    cb(results)
  }
  const createFilter = (queryString) => {
    return (restaurant) => {
      console.log(restaurant)
      return (
        restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      )
    }
  }

  const WHGetPageData1 = async () => {
    const params = {
      pageNo: 1,
      pageSize: 10,
      wheres: `[{"name":"ModuleId","value":"","displayType":"equal"}]`,
      export: true,
      moduleType: 'ModuleId',
      sort: 'SortCode',
      order: 'ASC',
      search: '',
    }
    const data = await GetPageDataVisit(params)
    if (data.data.rows && data.data.rows.length > 0) {
      data.data.rows.map((item) => {
        item.value = item.FullName
      })
    }
    WHdata.value = data.data.rows
  }
  WHGetPageData1()
  const BaseGetPageData1 = async () => {
    const params = {
        pageNo: 1,
        pageSize: 100,
        tableName: '',
        sort: '',
        order: '',
        wheres: '',
        export: true,
        value: '',
    }
    const data = await BaseGetPageData(params)
    // if (data.data.rows && data.data.rows.length > 0) {
    //   data.data.rows.map((item) => {
    //     item.value = item.FullName
    //   })
    // }
    DWdata.value = data.data.rows
  }
  BaseGetPageData1()
  // 下载物资表
  const download = async () => {
    const data = await Wms_ItemStockDown()
    if (data) {
      console.log(data)
      const blob = new Blob([data])
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.download = `物资库存管理.xlsx`
      link.href = url
      link.click()
    }
  }

  // 导出
  const exportFn = async () => {
    listLoading.value = true
    searchInfo.pageNo = 1
    if (
      itemname.value.trim() !== '' ||
      itemcode.value.trim() !== '' ||
      storageLocation.value.trim() !== '' ||
      whUnit.value.trim() !== '' ||
      batchNo.value.trim() !== '' ||
      whManage.value.trim() !== '' ||
      wsCode.value.trim() !== '' ||
      stockStatus.value.trim() !== ''
    ) {
      const arr = []
      itemname.value.trim() !== '' &&
        arr.push({
          name: 'ItemName',
          value: itemname.value,
          displayType: 'like',
        })
        wsCode.value.trim() !== '' &&
        arr.push({
          name: 'WSCode',
          value: wsCode.value,
          displayType: 'like',
        })
      stockStatus.value.trim() !== '' &&
        arr.push({
          name: 'StockStatus',
          value: stockStatus.value,
          displayType: 'like',
        })
      batchNo.value.trim() !== '' &&
        arr.push({
          name: 'BatchNo',
          value: batchNo.value,
          displayType: 'like',
        })
      whManage.value.trim() !== '' &&
        arr.push({
          name: 'WHManage',
          value: whManage.value,
          displayType: 'like',
        })
      itemcode.value.trim() !== '' &&
        arr.push({
          name: 'ItemCode',
          value: itemcode.value,
          displayType: 'like',
        })
      storageLocation.value.trim() !== '' &&
        arr.push({
          name: 'StorageLocation',
          value: storageLocation.value,
          displayType: 'like',
        })
      whUnit.value.trim() !== '' &&
        arr.push({
          name: 'WHUnit',
          value: whUnit.value,
          displayType: 'like',
        })
      // dateTime.value &&
      //     arr.push({
      //         name: 'ArrivalTime',
      //         value: dateTime.value!=null ? dateTime.value[0]:'',
      //         displayType: 'ThanOrEqual',
      //       })
      //     arr.push({
      //         name: 'ArrivalTime',
      //         value: dateTime.value!=null ? dateTime.value[1]:'',
      //         displayType: 'LessOrequal',
      // })
      searchInfo.value = itemname.value
      searchInfo.wheres = JSON.stringify(arr)
    } else {
      searchInfo.value = ''
      searchInfo.wheres = `[{"name":"ItemName","value": '',"displayType":"like"}]`
    }
    // searchInfo.wheres = `[{"name":"ItemName","value":"${itemname.value}","displayType":"like"}]`
    const data = await Wms_ItemStockExport(searchInfo)
    const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
    const blob = new Blob([data])
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.download = `物资库存管理${time}.xlsx`
    link.href = url
    link.click()
    listLoading.value = false
  }
  const handleError = () => {}
  const beforeUpload = () => {}
  const uploadFn = async () => {
    headers.value = headers.value = {
      Authorization: `Bearer ${token}`,
    }
    action.value = `${baseURL}/Wms_ItemStock/Import`
  }
  const handleSuccess = (data) => {
    console.log(data)
    if (data.code === '200') {
      ElMessage({
        message: data.message,
        type: 'success',
      })
      gettableData()
    } else {
      ElMessage({
        message: data.message,
        type: 'error',
      })
    }
  }
  const search = (val: any) => {
    console.log(date.value)
    searchInfo.pageNo = 1
    stockQty.value = stockType.value === '' ? '' : stockQty.value
    if (
      itemname.value.trim() !== '' ||
      itemcode.value.trim() !== '' ||
      storageLocation.value.trim() !== '' ||
      whUnit.value.trim() !== '' ||
      stockQty.value.trim() !== '' ||
      batchNo.value.trim() !== '' ||
      whManage.value.trim() !== '' ||
      wsCode.value.trim() !== '' ||
      stockStatus.value.trim() !== ''
    ) {
      const arr = []
      // itemname.value.trim() !== '' &&
      //   arr.push({
      //     name: 'ItemName',
      //     value: itemname.value,
      //     displayType: 'like',
      //   })
      itemcode.value.trim() !== '' &&
        arr.push({
          name: 'ItemCode',
          value: itemcode.value,
          displayType: 'like',
        })
      wsCode.value.trim() !== '' &&
        arr.push({
          name: 'WSCode',
          value: wsCode.value,
          displayType: 'like',
        })
      stockStatus.value.trim() !== '' &&
        arr.push({
          name: 'StockStatus',
          value: stockStatus.value,
          displayType: 'like',
        })
      batchNo.value.trim() !== '' &&
        arr.push({
          name: 'BatchNo',
          value: batchNo.value,
          displayType: 'like',
        })
      whManage.value.trim() !== '' &&
        arr.push({
          name: 'WHManage',
          value: whManage.value,
          displayType: 'like',
        })
      storageLocation.value.trim() !== '' &&
        arr.push({
          name: 'StorageLocation',
          value: storageLocation.value,
          displayType: 'like',
        })
      whUnit.value.trim() !== '' &&
        arr.push({
          name: 'WHUnit',
          value: whUnit.value,
          displayType: 'like',
        })
      stockQty.value.trim() !== '' &&
        arr.push({
          name: 'StockQty',
          value: stockQty.value,
          displayType: stockType.value,
        })
      //   dateTime.value &&
      //     arr.push({
      //         name: 'ArrivalTime',
      //         value: dateTime.value!=null ? dateTime.value[0]:'',
      //         displayType: 'ThanOrEqual',
      //       })
      //     arr.push({
      //         name: 'ArrivalTime',
      //         value: dateTime.value!=null ? dateTime.value[1]:'',
      //         displayType: 'LessOrequal',
      // })
      searchInfo.value = itemname.value
      searchInfo.wheres = JSON.stringify(arr)
    } else {
      searchInfo.value = ''
      searchInfo.wheres = `[{"name":"ItemName","value": '',"displayType":"like"}]`
    }
    if (val === 'seach') {
      searchInfo.value = searchChild.value
      searchInfo.wheres = `[{"name":"ItemName","value": ${searchChild.value},"displayType":"like"}]`
    }
    // searchInfo.date = date.value
    gettableData()
  }
  const search1 = (val: any) => {
    console.log('xxxx')
    searchInfo1.pageNo = 1

    if (val === 'seach') {
      searchInfo1.value = searchChild.value
      searchInfo1.wheres = `[{"name":"ItemName","value": ${searchChild.value},"displayType":"like"}]`
    }
    // searchInfo.date = date.value
    gettableData1()
  }

  const dialogVisible = ref(false)
  const dialogVisible1 = ref(false)
  const detail: any = ref({})
  const showDialog = (row: any) => {
    detail.value = row
    console.log(detail.value)

    dialogVisible.value = true
  }
  const eitFn = (row) => {
    wmscodename.value = row.WSCode
    detail.value = row
    dialogVisible3.value = true
  }
  const confirm3 = async () => {
    console.log(detail.value)
        tranwscodes()
  }
 const tranwscodes = async () => {
     const params = {
      isid:detail.value.ISID,
      wsCode:WHdataId.value,
     }
     const data = await tranwscode(params)
     if(data.code === '200') {
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
     }
     dialogVisible3.value = false
     gettableData()

  }
  const batchFn = () => {
    seletceInfo.value = ''
    newFullName.value = ''
    newprice.value = ''
    newitemUnit.value = ''
    selectArr.value = []
    dialogVisible1.value = true
  }
  const batchFn1 = () => {
    seletceInfo.value = ''
    newFullName.value = ''
    newprice.value = ''
    newitemUnit.value = ''
    selectArr.value = []
    dialogVisible6.value = true
  }
  const batchDPFn = () => {
    console.log(selectArrList.value)
    if(selectArrList.value.length<=0) {
      ElMessage({
          message: '请选择至少一条要修改数据',
          type: 'warning',
        })
      return
    }
    dialogVisible2.value = true
  }
  const batchDPFn2 = () => {
    console.log(selectArrList.value)
    if(selectArrList.value.length<=0) {
      ElMessage({
          message: '请选择至少一条要修改数据',
          type: 'warning',
        })
      return
    }
    dialogVisible6.value = true
  }
  const dateEtitFn = (row) => {
    selectArrList.value = [row]
    dialogVisible4.value = true
  }
  const dateBatchFn = () => {
    if(selectArrList.value.length<=0) {
      ElMessage({
          message: '请选择至少一条要修改数据',
          type: 'warning',
        })
      return
    }
    dialogVisible4.value = true
  }
  const handleClose1 = () => {
    dialogVisible1.value = false
  }
  const handleClose2 = () => {
    dialogVisible2.value = false
  }
  const handleClose6 = () => {
    dialogVisible6.value = false
  }
  const handleClose4 = () => {
    dialogVisible4.value = false
  }
  const handleClose3 = () => {
    dialogVisible3.value = false
  }
  const handleConfirm = async () => {
      console.log('aaaa')
      dialogVisible.value = false
      gettableData()

  }
  const handleClose = () => {
    dialogVisible.value = false
  }
</script>

<style lang="scss" scoped>
  .tpl-container {
    .color_494949 {
      color: #494949;
      width: 85px;
      display: inline-block;
      text-align: end;
    }

    .noData {
      text-align: center;
      font-size: 16px;
      color: gray;
    }
    .w192 {
      width: 192px;
    }
    .w120 {
      width: 120px;
    }
    .w200 {
      width: 200px;
    }
    .mb20 {
      margin-bottom: 20px;
    }
    .flex_align {
      display: flex;
      align-items: center;
    }
    .mr20 {
      margin-right: 20px;
    }
    .mt20 {
      margin-top: 20px;
    }
    .mt20 {
      margin-top: 20px;
    }
    .mr10 {
      margin-right: 10px;
    }
    .w400 {
      width: 100%;
    }
    .mt10 {
      margin-top: 10px;
    }
    .w90 {
      width: 100px;
      display: inline-block;
      text-align: right;
    }
    .img-container {
      display: flex;
      // justify-content: center;

      .img {
        width: 100px;
      }
    }

    .condition-container {
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      .condition {
        margin-right: 14px;
        margin-bottom: 10px;
      }
    }
  }
  .el-table {
    & ::v-deep th.el-table__cell,
    ::v-deep td.el-table__cell {
      // 设置position 使得 子元素不与其产生新的层叠关系
      position: static;
    }
  }
  .ml-upload {
    display: inline-block;
    margin-left: 10px;
    vertical-align: bottom;
    margin-right: 10px;
  }
  .add {
      margin-bottom: 10px;
      text-align: left;
    }
  .mr14 {
    margin-right:14px;
  }
  .ml10 {
    margin-left: 10px;
  }
  .w164 {
    width: 164px;
  }
  .color_red {
      color: #f56c6c;
    }
  ::v-deep .el-tag {
    margin-bottom: 5px;
  }
</style>
